﻿// --------------------------------
// <copyright file="Tools.cs" company="TRONSoft">
//     Copyright (c) TRONSoft.
// </copyright>
// <license>
//   This source code is subject to terms and conditions of the Microsoft
//   Public License. A copy of the license can be found in the License.html
//   file at the root of this distribution. If you cannot locate the
//   Microsoft Public License, please send an email to dlr@microsoft.com.
//   By using this source code in any fashion, you are agreeing to be bound 
//   by the terms of the Microsoft Public License. You must not remove this
//   notice, or any other, from this software.
// </license>
// <author>Tron</author>
// ---------------------------------

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;

namespace Actucal
{
    static class Tools
    {
        public static void SaveDataAsBinary<T>(string path, T data)
        {
            BinaryFormatter serializer = new BinaryFormatter();
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                serializer.Serialize(fs, data);
                fs.Flush();
            }
        }

        public static T LoadDataAsBinary<T>(string path)
        {
            if (File.Exists(path))
            {
                BinaryFormatter serializer = new BinaryFormatter();
                using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    try
                    {
                        return (T)serializer.Deserialize(fs);
                    }
                    catch (Exception)
                    {
                        return default(T);
                    }
                } 
            }

            return default(T);
        }

        public static void SaveData<T>(string path, T data)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StreamWriter sw = new StreamWriter(path))
            {
                serializer.Serialize(sw, data);
                sw.Flush();
            }
        }

        public static T LoadData<T>(string path)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StreamReader sr = new StreamReader(path))
            {
                return (T)serializer.Deserialize(sr);
            }
        }
    }
}
